
package com.huawei.housekeeper.gateway.filter;

import com.huawei.housekeeper.gateway.util.HeaderUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.cors.reactive.CorsUtils;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;


import reactor.core.publisher.Mono;

/**
 * cors解决
 *
 * @since 2021-12-16
 */
@Component
public class CorsFilter implements WebFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange swe, WebFilterChain wfc) {
        ServerHttpRequest request = swe.getRequest();
        if (!CorsUtils.isCorsRequest(request)) {
            return wfc.filter(swe);
        }
        ServerHttpResponse response = swe.getResponse();
        HttpHeaders headers = response.getHeaders();
        HeaderUtil.setHeaders(headers);
        if (request.getMethod() == HttpMethod.OPTIONS) {
            response.setStatusCode(HttpStatus.OK);
            return Mono.empty();
        }
        return wfc.filter(swe);
    }
}